package com.cf.web.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化时的配置（如果有的话）
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        // 获取请求来源的 Origin (可以动态设置 CORS 头)
        String origin = httpRequest.getHeader("Origin");
        httpResp.setHeader("Access-Control-Allow-Origin", "*");
        // 设置 CORS 相关的响应头
        httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");  // 允许的方法
        httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");  // 允许的请求头
//        httpResp.setHeader("Access-Control-Allow-Credentials", "true");  // 允许携带凭证（如 Cookies）

        // 处理预检请求（OPTIONS）
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 放行请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}
